import {getRightFromAPI} from "../../server";
import {strGetUrlParam} from "ls-base-lib";
import {vueGetParamFromQuery} from "ls-base-lib";

const defaultRight = ['lr_add', 'lr_edit', 'lr_delete', 'lr_import', 'lr_export', 'lr_enableDisable'] as const;

const ModuleKeyName = 'masmcode';
const MissModuleKeyName = `按钮权限获取失败，URL参数中缺失模块名称信息：${ModuleKeyName}`;

export type Rights = { [P in (typeof defaultRight)[number]]: boolean }

export interface ModuleAuthorityType {
  ButtonRight: ButtonRightType[]
}

export interface ButtonRightType {
  F_EnCode: string
}


//获取默认权限，默认无任何权限，用于data
export function getDefaultRight() {
  const result: Rights = {} as any;
  defaultRight.forEach((x) => {
    result[x] = false;
  });
  return result
}

export function getModuleCodeFromQuery(query: Record<string, (string | null) | (string | null)[]>) {
  const moduleCode = vueGetParamFromQuery(query, ModuleKeyName);
  if (!moduleCode)
    console.warn(MissModuleKeyName);
  return moduleCode
}

//获取小安易连模块的按钮权限，用于method或create
export async function getRight(moduleCode?: string): Promise<Rights | undefined> {
  const _moduleCode = moduleCode || strGetUrlParam(ModuleKeyName);
  if (_moduleCode) {
    const result = await getRightFromAPI(_moduleCode);
    if (result) {
      const buttonRight = result.ButtonRight;
      const rights = getDefaultRight();
      buttonRight.forEach(x => {
        if (x.F_EnCode in rights) {
          // @ts-ignore
          rights[x.F_EnCode] = true;
        }
      })
      return rights;
    }
  } else
    console.warn(MissModuleKeyName);
}
